package org.tea.springdata.mina.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 * @author: John zhang
 * @version: 0.1
 */
public class Client {
	private static final Log log = LogFactory.getLog(Client.class);

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Create TCP/IP connector.
		NioSocketConnector connector = new NioSocketConnector();
		// 创建接收数据的过滤器
		DefaultIoFilterChainBuilder chain = connector.getFilterChain();
		// 设定这个过滤器将一行一行(/r/n)的读取数据
		chain.addLast("objectCodec", new ProtocolCodecFilter(new TextLineCodecFactory( Charset.forName("UTF-8"), LineDelimiter.NUL, LineDelimiter.NUL ) ));
		// 设定服务器端的消息处理器:一个SamplMinaServerHandler对象,
		connector.setHandler(new ObjectClientHandler());
		// Set connect timeout.
		connector.setConnectTimeoutCheckInterval(30);
		// 连结到服务器:
		try {
			ConnectFuture cf = connector.connect(new InetSocketAddress("localhost", 4848));
			cf.awaitUninterruptibly();
			IoSession session = cf.getSession();
			BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
			while (true) {
				String input = systemIn.readLine();
				if (input == "" || "quit".equalsIgnoreCase(input.trim())) {
					WriteFuture future = session.write(input);
					future.awaitUninterruptibly(3000);
					System.out.println("send quit cmd successfully");
					session.getCloseFuture().awaitUninterruptibly();
					connector.dispose();
					System.exit(0);
				}
				
				session.setAttribute("publicKey", "abcdefghijklmn");
				WriteFuture future = session.write(input);
				future.awaitUninterruptibly(3000);
				System.out.println("send " + input + "  successfully");
				// Thread.sleep(10000);
			}
		} catch (Exception e) {
			connector.dispose();
			log.error("未能连接到服务器");
		}
	}

}